// pages/gameLineup/gameLineup.js
const app = getApp();
var myCanvasWidth, myCanvasHeight, posterWidth, posterHeight;
var items = [];
var index = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    img: "../../images/lineup-bg.png",
    posterHeight: 0,
    topHeight: 0,
    bottompHeight:0,
    lineupCenHeight:0,
    teamId: [],
    teamName: [],
    teamIndex: 0,
    session_key:'',
    playlList:[],
    canvasTemImg:'',
    dataImaage:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var _topheight = that.data.topHeight;
    var _bottomheight = that.data.bottompHeight;
    //获取头部底部高度
    var query = wx.createSelectorQuery();
    query.selectAll('.lineup-orther').boundingClientRect(function (e) {
      that.setData({
        topHeight: e[0].height,
        bottompHeight: e[1].height
      })
      _topheight = e[0].height;
      _bottomheight = e[1].height;

      // 获取手机信息 设置画布大小
      wx.getSystemInfo({
        success: function (res) {
          myCanvasWidth = res.screenWidth
          myCanvasHeight = res.windowHeight//可使用窗口高度
          posterWidth = Math.round(res.screenWidth * 0.68)  //计算让画布图片自适应
          posterHeight = Math.round(posterWidth * 1920 / 1080)
          
          that.setData({
            myCanvasWidth: myCanvasWidth,
            myCanvasHeight: myCanvasHeight,
            posterHeight: posterHeight,
            lineupCenHeight: myCanvasHeight
          })

        },
      })

    }).exec();

    that.setData({
      session_key: wx.getStorageSync("token")
    })
    //获取球队信息
    wx.request({
      url: app.globalData.httpsPath + '/user/team',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        token: that.data.session_key
      },
      //请求后台数据成功  
      success: function (res) {
        var teamidArry = [];
        var teamArry = [];
        var _index = 0;
        var _createTeam = res.data.data.data;
        for (var i = 0; i < _createTeam.length; i++) {
          teamidArry.push(_createTeam[i].team_id);
          teamArry.push(_createTeam[i].team.name);
          if (options.teamid == _createTeam[i].team_id){//判断获取的id与数据库里的相等
            _index = i
          }
        }
        that.setData({
          teamId: teamidArry,
          teamName: teamArry,
          teamIndex :_index
        })
      }
    })
    //球队队员
    wx.request({
      url: app.globalData.httpsPath + '/team/users',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        token: that.data.session_key,
        team_id: options.teamid
      },
      //请求后台数据成功  
      success: function (res) {
        var team_member = res.data.data;
        for (var i=0; i < team_member.length;i++){
          team_member[i].active=false;
          team_member[i].top = 50;
          team_member[i].left = 30;
          team_member[i].x = 0;
          team_member[i].y = 0;
          team_member[i]._postion = "static";
          team_member[i].fontcolor = "#000000";
        }
        items = team_member;
        that.setData({
          playList: team_member
        })
      }
    })
  },
  //切换球队信息
  bindTeamChange:function(e){
    var that = this;
    that.setData({
      teamIndex: e.detail.value
    })
    var teamId = that.data.teamId[e.detail.value];
    var _key = that.data.session_key;
    //球队队员
    wx.request({
      url: app.globalData.httpsPath + '/team/users',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        token: _key,
        team_id: teamId
      },
      //请求后台数据成功  
      success: function (res) {
        var team_member = res.data.data;
        for (var i = 0; i < team_member.length; i++) {
          team_member[i].active = false;
          team_member[i].top = 50;
          team_member[i].left = 30;
          team_member[i].x = 0;
          team_member[i].y = 0;
          team_member[i]._postion = "static";
        }
        items = team_member;
        that.setData({
          playList: team_member
        })
      }
    })
  },
  //元素移动开始
  moveStart:function(e){
    var that = this;
    items = that.data.playList;
    
    for (let i = 0; i < items.length; i++) { //找到被点击的数据
      items[i].active = false;
      if (e.currentTarget.id == items[i].id) {
        index = i; //记录下标
        items[index].active = true; //开启点击属性
        items[index]._postion = "absolute";
        items[index].fontcolor ="#ffffff"
      }
    }

    items[index].lx = e.touches[0].clientX; // 记录点击时的坐标值
    items[index].ly = e.touches[0].clientY;
    that.setData({
      playList: items
    })
  },
  //元素移动
  onMove: function(e) {

    var that = this;
    //移动时的坐标值也写数据属性里
    items[index]._lx = e.touches[0].clientX;
    items[index]._ly = e.touches[0].clientY;

    //追加改动值
    items[index].left += items[index]._lx - items[index].lx; // x方向
    items[index].top += items[index]._ly - items[index].ly; // y方向
    items[index].x += items[index]._lx - items[index].lx;
    items[index].y += items[index]._ly - items[index].ly;

    //把新的值赋给老的值
    items[index].lx = e.touches[0].clientX;
    items[index].ly = e.touches[0].clientY;

    that.setData({ //赋值就移动了
      playList: items,
    })

  },
  //元素移动结束
  touchend: function (e){
    var that = this;
    var _height = 0, new_height = 0;
    //获取内容高度
    var _mainHieght = that.data.lineupCenHeight - that.data.topHeight - that.data.bottompHeight;
    //获取元素距上的距离
    var box_top = items[index].top;
    items[index].active = false;//结束以后去掉选中状态
    //重新还原位置
    if (box_top > _mainHieght){
      items[index].left = 30; 
      items[index].top = 50; 
      items[index].active = false;
      items[index]._postion ="static";
      items[index].fontcolor = "#000000"
    }
    that.setData({ //赋值
      playList: items,
    })
  },
  //保存图片
  clickMe: function () { 
    // var self = this;
    // let maskCanvas = wx.createCanvasContext("lineupCanvas", this);
    // var query = wx.createSelectorQuery()
    // var imgbgHeight = self.data.myCanvasHeight - self.data.topHeight - self.data.bottompHeight;
    // console.info(items[0].avatar);
    // var num = 1; // 追加到canvas的比例
    // maskCanvas.save();//保存绘图上下文
    // maskCanvas.beginPath();//创建一个路径
    // maskCanvas.setFillStyle('#ffffff');//填充背景颜色
    // maskCanvas.fillRect(0, 0, self.data.myCanvasWidth, self.data.myCanvasHeight);//填充背景
    // maskCanvas.fillRect(0, 0, self.data.myCanvasWidth, self.data.topHeight);//top矩形
    // maskCanvas.drawImage(self.data.img, 0, self.data.topHeight, self.data.myCanvasWidth, imgbgHeight); //绘制图片
    // maskCanvas.setFillStyle('#f6f7fa')
    // maskCanvas.fillRect(0, self.data.topHeight + imgbgHeight, self.data.myCanvasWidth, self.data.bottompHeight);//bottom矩形
    
    // maskCanvas.setFontSize(16);//设置字体大小
    // maskCanvas.setFillStyle("#333333");//字体颜色
    // maskCanvas.setTextAlign('center');//字体位置
    // maskCanvas.fillText('选择球队：球队测试俱乐部', self.data.myCanvasWidth / 2, 30); //创建字体

    // maskCanvas.translate(items[0].left - 18, items[0].top)
    // maskCanvas.drawImage(items[0].avatar, items[0].left, items[0].top, 36 * num, 36 * num);
    // maskCanvas.arc(0, 0, (50 / 2) * num, 0, 2 * Math.PI, false);
    // maskCanvas.clip(); //截取

    // maskCanvas.setFontSize(12);//设置字体大小
    // maskCanvas.setTextAlign('left');//字体位置
    // maskCanvas.setFillStyle("#000000");//字体颜色
    // maskCanvas.fillText(items[0].name, items[0].left, items[0].top + 36); //创建字体
    // maskCanvas.fillText(items[0].name, 0, 0); //创建字体
    
    // console.info(items[0].top);

    // maskCanvas.closePath();
    // maskCanvas.stroke();
    // maskCanvas.draw();

    //获取当前元素dom节点
    // items.forEach((currentValue, index) => {
    //   let query = wx.createSelectorQuery();
    //   query.select('#player-' + currentValue.id).boundingClientRect(function (res) {
    //     // console.info(res);
    //     maskCanvas.save();
    //     maskCanvas.beginPath();
    //     //平移变换
    //     maskCanvas.translate((res.left + 6 + 50 / 2), (res.top + 6 + 55 / 2)) 
    //     maskCanvas.arc(0, 0, (50 / 2) * num, 0, 2 * Math.PI, false);
    //     maskCanvas.clip(); //截取
    //     maskCanvas.drawImage(currentValue.avatar, res.left, res.top, 50 * num, 55 * num);

        
    //     // maskCanvas.translate((res.left + 6 + 50 / 2), (res.top + 6 + 55 / 2))   
    //     // maskCanvas.setFontSize(12);//设置字体大小
    //     // maskCanvas.setFillStyle("#000000");//字体颜色
    //     // maskCanvas.fillText(currentValue.name, 0, 0 ); //创建字体

    //     maskCanvas.restore();//恢复之前保存的绘图上下文。
    //     maskCanvas.draw(true);//将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中。

    //   }).exec(function (res) { });
    // })

    // maskCanvas.draw();
    // setTimeout(function () {
    //   wx.canvasToTempFilePath({
    //     canvasId: 'lineupCanvas',
    //     fileType: 'jpg',
    //     success: res => {
    //       console.log(res.tempFilePath);
    //       self.setData({
    //         canvasTemImg: res.tempFilePath
    //       })
    //       wx.saveImageToPhotosAlbum({
    //         filePath: res.tempFilePath,
    //         success() {
    //           wx.showToast({
    //             title: '图片已保存至相册'
    //           });
    //           self.setData({
    //             dataImaage: res.tempFilePath,
    //           })
    //           //存入服务器
    //         // wx.uploadFile({
    //         //   url: 'a.php', //接口地址
    //         //   filePath: res.tempFilePath,
    //         //   name: 'file',
    //         //   formData: {                                 //HTTP 请求中其他额外的 form data 
    //         //     'user': 'test'
    //         //   },
    //         //   success: function (res) {
    //         //     console.log(res);

    //         //   },
    //         //   fail: function (res) {
    //         //     console.log(res);
    //         //   },
    //         //   complete: function (res) {
    //         //   }
    //         // });
    //         }
    //       });
    //     }
    //   })
    // }, 2000);

  },

})